# coding:utf-8
import re
import json
import requests
from config import expdata
from config import usernames

def exponeuser(username):
    session = requests.Session()  # 构造Session
    for k in range(10):
        try:
            resp = session.post('http://vsew.jmu.edu.cn/auth/login',
                                {"email": str(username), "password": str(username), "next": "/course"})  # 登录
        except requests.exceptions.ConnectionError as e:
            print("Error:" + str(e) + str(k) + "/10, try again")
            continue
        try:
            print(str(username) + " login " + resp.json()['message'])
            if resp.json()['message'] == "账号或密码错误":
                return resp.json()['message']
            break
        except json.JSONDecodeError as e:
            print("Error:" + str(e) + str(k) + "/10, try again")

    ids = []
    for i in range(1, 4):  # 获取实验id
        resp = session.get('http://vsew.jmu.edu.cn/course/module/list?page=' + str(i) + '&page_size=20&category_id=&child_category_id=')
        list_data = resp.json()['data']['list']['data']
        if len(list_data) == 0:
            break
        for li in list_data:
            ids.append(li['id'])
    # ids = [52, 6, 3, 4, 5, 7, 10, 9, 8, 12, 11, 17, 13, 18, 14, 16, 15, 23, 24, 25]
    for id in ids:
        resp = session.get('http://vsew.jmu.edu.cn/course/module/' + str(id))
        module_html = resp.text
        a = module_html.find('window.module = {')
        b = module_html.find('\n            </script>', a)
        modules = json.loads(module_html[a + 16:b])
        print("GET " + modules['name'] + ":OK")
        for chapter in modules['chapters']:
            for content in chapter['contents']:
                print(" GET " + content['model']['name'], end='')  # 进入文本或实操
                if content["learn_status"] == 1:
                    print(" -- 已完成，跳过!")
                    continue
                playgroundurl = "http://vsew.jmu.edu.cn/course/module/" + str(modules['id']) + "/playground/" + str(content['chapter_id']) + "/" + str(
                    content['id'])
                resp = session.get(playgroundurl)
                if content['model']['type'] == '1':  # 文本
                    print("（文本）：", end="")
                    resp = session.post(playgroundurl + "/doc", data={"action": "5"})  # action:5
                    print(resp.json()['message'], end='->')
                    resp = session.post(playgroundurl + "/doc", data={"action": "6"})  # action:6
                    print(resp.json()['message'])

                elif content['model']['type'] == '0':  # 实操
                    print("（实操）")
                    playground_html = resp.text
                    a = playground_html.find("window.data = {")
                    b = playground_html.find("\n", a)
                    playground_data = json.loads(playground_html[a + 14:b])
                    experimental_principle = ''  # 存储实验原理文本
                    for playground_content in playground_data['scene']['scene']['contents']:  # 实验页内容
                        title = playground_content.get('title')
                        if playground_content["is_view"] == False:
                            for i in range(10):
                                try:
                                    print("  POST " + title)
                                    resp = session.post(playgroundurl + "/view/" + str(playground_content['id']), data={"action": "9"})
                                    if len(resp.text) > 1:
                                        print(re.findall("<title.*?\/title>", resp.text)[0], end='--')
                                    break
                                except requests.exceptions.ConnectionError as e:
                                    print("Error:"+str(e)+str(i)+"/10, try again")
                        else:
                            print("  " + title)

                        if playground_content["is_pass"] == True:
                            print("   --已通过,不再提交,跳过！")
                            continue

                        if title == '实验原理':  # 遇到实验原理，记录实验原理内容
                            experimental_principle = str(playground_content.get('content'))
                        elif title == '实验总结':  # 遇到实验总结，以实验原理内容为答案提交
                            print("   POST Summary", end=":")
                            resp = session.post(playgroundurl + "/answer/" + str(playground_content['id']) + "?action=8",
                                                data={"answer": experimental_principle})
                            print(resp.json()['message'])
                        elif len(playground_content['questions']) > 0:  # 存在问题
                            answer_list = []
                            for question in playground_content['questions']:
                                print("   ID:" + str(question['id']), end=":")
                                answer = expdata.get(str(question['id']))
                                if answer is None:
                                    answer = ""
                                print(answer)
                                answer_list.append({"id": str(question['id']), "answer": answer})  # TODO：answer
                            for i in range(10):
                                try:
                                    print("   POST Answer", end=":")
                                    resp = session.post(playgroundurl + "/answer/" + str(playground_content['id']) + "?action=7", data=json.dumps(answer_list))
                                except requests.exceptions.ConnectionError as e:
                                    print("Error:"+str(e)+str(i)+"/10, try again")
                                    continue
                                try:
                                    resp_json = resp.json()
                                    if resp_json.get('data') != None:
                                        print(resp_json['data']['result'])
                                        print("   Return Answer:"+str(resp_json['data']['answer']))

                                        for result in resp_json['data']['result']:  # 记录错题
                                            if result['result'] == False:
                                                with open('Flase.txt', "a") as f:
                                                    f.write(modules['name']+"->"+content['model']['name']+"->"+str(resp_json['data'])+"\n")
                                    else:
                                        print(resp_json['message'])
                                    break
                                except Exception as e:
                                    print("Error:"+str(e)+re.findall("<title.*?\/title>", resp.text)[0])
                                    continue


if __name__ == '__main__':
    for username in usernames:
        exponeuser(username)
    exponeuser(201421122117)
